<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AI Chat</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    #chat-box {
      border: 1px solid #ccc;
      padding: 10px;
      height: 300px;
      overflow-y: scroll;
    }
    .message {
      margin: 10px 0;
    }
    .user {
      color: blue;
    }
    .bot {
      color: green;
    }
  </style>
</head>
<body>
<h1>AI Chat</h1>
<div id="chat-box"></div>
<form id="chat-form">
  <input type="text" id="message" placeholder="Type your message..." required />
  <button type="submit">Send</button>
</form>

<script>
  document.getElementById('chat-form').addEventListener('submit', function(event) {
    event.preventDefault();
    const message = document.getElementById('message').value.trim();
    if (message === "") {
      alert("Message content cannot be null or blank");
      return;
    }
    addMessageToChatBox(message, 'user');
    startSSE(message);
    document.getElementById('message').value = '';
  });

  function addMessageToChatBox(message, sender) {
    const chatBox = document.getElementById('chat-box');
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message', sender);
    messageDiv.textContent = message;
    chatBox.appendChild(messageDiv);
    chatBox.scrollTop = chatBox.scrollHeight;
  }

  function startSSE(message) {
    const sse = new EventSource(`/ai/stream/chats?msg=${encodeURIComponent(message)}`);
    sse.onmessage = function(event) {
      addMessageToChatBox(event.data, 'bot');
    };
    sse.onerror = function(error) {
      console.error('SSE Error:', error);
      sse.close();
    };
  }
</script>
</body>
</html>
